package com.example.demotest.controller;

import com.example.demotest.pojo.*;
import com.example.demotest.pojo.dto.ChangePasswordDto;
import com.example.demotest.pojo.dto.UserDto;
import com.example.demotest.pojo.dto.UserProfileDto;
import com.example.demotest.service.IUserService;
import com.example.demotest.util.AliOssUtil;
import com.example.demotest.util.JWT;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JWT jwt;//于登录验证和提取用户信息

    @Autowired
    private AliOssUtil aliOssUtil;


    //REST
    //增加
    @PostMapping
    public ResponseMessage<User> add(@Validated @RequestBody UserDto user){
        System.out.println("信息接受成功");
        User userNew = userService.add(user);
        return ResponseMessage.success(userNew);
    }

    // 注册接口（安全版）
    @PostMapping("/register")
    public ResponseMessage<User> register(@Validated @RequestBody UserDto userDto) {
        System.out.println("信息接受成功1111");
        User newUser = userService.register(userDto);
        return ResponseMessage.success(newUser);
    }

    //登录
    @PostMapping("/login")
    public ResponseMessage<User> login(@RequestBody UserDto userDto) {
        return userService.login(userDto);
    }

    //登录获取token
    @GetMapping("/info")
    public ResponseMessage<UserDto> getOneUser(HttpServletRequest request) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || auth.getPrincipal() == null) {
            return ResponseMessage.error(404, "未登录");
        }

        Integer userId = (Integer) auth.getPrincipal();

        // ✅ 从请求头中获取 token
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 去掉 "Bearer "
        }

        return ResponseMessage.successWithToken(userService.getUser(userId), token);
    }

    // 查询某个用户信息，必须登录后才能访问
    @GetMapping("/{userId}")
    public ResponseMessage<UserDto> get(@PathVariable Integer userId, HttpServletRequest httpRequest) {
        String token = jwt.extractToken(httpRequest);
        if (token == null) {
            return ResponseMessage.error(401, "未登录或Token无效");
        }

        // 校验 token 是否有效
        Integer currentUserId = jwt.getUserIdFromToken(token);
        if (currentUserId == null) {
            return ResponseMessage.error(401, "Token非法或过期");
        }

        UserDto userNew = userService.getUser(userId);
        if (userNew == null) {
            return ResponseMessage.error(404, "用户不存在");
        }

        return ResponseMessage.success(userNew);
    }


    //修改
    @PutMapping
    public ResponseMessage<User> edit(@Validated @RequestBody UserDto user){
        User userNew = userService.edit(user);
        return ResponseMessage.success(userNew);
    }

    //删除用户
    @DeleteMapping("/{userId}")
    public ResponseMessage<User> delete(@PathVariable Integer userId){
        userService.delete(userId);
        return ResponseMessage.success();
    }

    //登录后查看用户信息
    @GetMapping("/profile")
    public ResponseMessage<UserProfile> getUserProfile(HttpServletRequest httpRequest){

        Integer userId = (Integer) httpRequest.getAttribute("userId");
        UserProfile userProfileNew = userService.getUserInformation(userId);
        return ResponseMessage.success(userProfileNew);
    }

    //登录后查看其他人信息
    @GetMapping("/profile/{userId}")
    public ResponseMessage<UserProfile> getOtherUserProfile(HttpServletRequest httpRequest,@PathVariable Integer userId){

        UserProfile userProfileNew = userService.getUserInformation(userId);
        if(userProfileNew == null){
            return ResponseMessage.error(404, "用户不存在");
        }
        return ResponseMessage.success(userProfileNew);
    }

    //登录后更改自己的用户信息
    @PutMapping("/profile")
    public ResponseMessage<UserProfile> editProfile(@RequestBody UserProfileDto dto, HttpServletRequest httpRequest) {
        String token = jwt.extractToken(httpRequest);  // 从请求中提取 token
        if (token == null) {
            throw new RuntimeException("缺少或非法的 Token");
        }

        Integer userId = jwt.getUserIdFromToken(token);

        return ResponseMessage.success(userService.updateUserProfile(userId, dto));
    }

    //退出登录
    @PostMapping("/logout")
    public ResponseMessage<?> logout(@RequestHeader("Authorization") String token) {
        System.out.println("用户退出，token = " + token);

        return ResponseMessage.success("已成功退出登录");
    }

    //修改密码
    @PutMapping("/password")
    public ResponseMessage<User> changePassword(@RequestBody ChangePasswordDto dto, HttpServletRequest httpRequest) {

        String token = jwt.extractToken(httpRequest);  // 从请求中提取 token
        if (token == null) {
            throw new RuntimeException("缺少或非法的 Token");
        }

        Integer userId = jwt.getUserIdFromToken(token);

        return ResponseMessage.success(userService.updateUserPassword(userId, dto));
    }

    //修改昵称
    @PutMapping("/info")
    public ResponseMessage<User> changeNickname(@RequestBody User dto, HttpServletRequest httpRequest) {

        String token = jwt.extractToken(httpRequest);  // 从请求中提取 token
        if (token == null) {
            throw new RuntimeException("缺少或非法的 Token");
        }

        Integer userId = jwt.getUserIdFromToken(token);

        return ResponseMessage.success(userService.updateUserNickname(userId, dto));
    }

    @CrossOrigin("http://localhost:8081")
    @PostMapping("/upload/image")
    public ResponseMessage<String> uploadUserAvatar(@RequestParam("file") MultipartFile file,
                                                    HttpServletRequest request) {
        try {
            // 解析 Token，获取用户 ID
            String token = jwt.extractToken(request);
            Integer userId = jwt.getUserIdFromToken(token);
            if (userId == null) {
                return ResponseMessage.error(401, "未登录或 token 无效");
            }

            // 获取原始文件名和扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = "avatar/" + UUID.randomUUID().toString() + extension;

            // 上传到 OSS 并获取 URL
            String fileUrl = aliOssUtil.upload(file.getBytes(), objectName);

            // 更新数据库中的头像信息
            userService.updateAvatar(userId, fileUrl);  // 👈 确保你实现了这个方法

            return ResponseMessage.success("头像上传成功", fileUrl);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseMessage.error("头像上传失败");
        }
    }


}
